﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Text;
using System.Linq;
using Newtonsoft.Json;
using T.FAS.Runtime.Base.Entity;
using T.FAS.Runtime.Expression.SPI;
using T.ServiceComponent.Log.SPI;
using T.ServiceComponent.Log.Client;
using T.FAS.Runtime.Base.Service;
using T.FAS.Runtime.Expression.Entity;

namespace T.FAS.Runtime.Expression.Plugin
{
    public class LogExecutor : DynamicObject, IDynamicActionAdapter
    {
        /// <summary>
        /// JS脚本动态调用Dynamic必备函数
        /// 脚本写法：ConfigCenter.();
        /// </summary>
        /// <param name="name">动态调用DynamicObject中的函数名称</param>
        /// <param name="args">参数信息，参数类型必须增加 params</param>
        /// <returns></returns>
        public dynamic DynamicInvoke(string name, params object[] args)
        {
            throw new FasException(ExprExceptionCode.NotSupported, "Unsupported Log." + name);
        }

        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out dynamic result)
        {
            result = DynamicInvoke(binder.Name, args);
            return true;
        }
        readonly ExprLogService service = new ExprLogService();
        public void Log(string obj)
        {
            Base.Common.LogUtil.Log(JsonConvert.SerializeObject(obj), "Expression");
        }
        public void DBLog(object obj)
        {
            service.AddDBLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"), obj);
        }
        public void DBLog(string tag, object obj)
        {
            service.AddDBLog(tag,obj);
        }
        public void LocalLog(object obj)
        {
            Base.Common.LogUtil.Log(JsonConvert.SerializeObject(obj), "Expression");
        }
        public void LocalLog(string tag, object obj)
        {
            Base.Common.LogUtil.Log("Tag:" +tag + ",Message:" + JsonConvert.SerializeObject(obj),"Expression");
        }
        public void BigDataLog(string tag, object obj)
        {
            using (var client = new LogLocalClient())
            {
                SysActionLog sysActionLog = new SysActionLog();
                sysActionLog.UserID = Base.Common.UserUtil.GetCurrentUserID();
                sysActionLog.DataKey = tag;
                sysActionLog.Description = JsonConvert.SerializeObject(obj);
                client.SendLogs(sysActionLog);
            }
        }
    }
}
